package com.he1618.boot3.app;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Iterator;

public class DynamicJsonToJava {

    public static void main(String[] args) {
        try {
            // JSON字符串示例，你可以从其他来源获取
            String jsonString = "{\"field1\":\"value1\", \"field2\":\"value2\", \"nested\":{\"field3\":\"value3\"}}";

            // 创建ObjectMapper实例
            ObjectMapper objectMapper = new ObjectMapper();

            // 将JSON字符串解析为JsonNode
            JsonNode jsonNode = objectMapper.readTree(jsonString);

            // 生成Java类的代码
            String generatedCode = generateJavaClass("GeneratedClass", jsonNode);

            // 输出生成的代码
            System.out.println(generatedCode);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String generateJavaClass(String className, JsonNode jsonNode) {
        StringBuilder codeBuilder = new StringBuilder();

        // 生成包名和类声明
        codeBuilder.append("public class ").append(className).append(" {\n");

        // 遍历JSON节点生成字段声明
        Iterator<String> fieldNames = jsonNode.fieldNames();
        while (fieldNames.hasNext()) {
            String fieldName = fieldNames.next();
            JsonNode fieldNode = jsonNode.get(fieldName);

            String fieldType = getJavaType(fieldNode);
            codeBuilder.append("    private ").append(fieldType).append(" ").append(fieldName).append(";\n");
        }

        // 生成类的结尾
        codeBuilder.append("}\n");

        return codeBuilder.toString();
    }

    private static String getJavaType(JsonNode jsonNode) {
        if (jsonNode.isTextual()) {
            return "String";
        } else if (jsonNode.isBoolean()) {
            return "boolean";
        } else if (jsonNode.isInt()) {
            return "int";
        } else if (jsonNode.isDouble()) {
            return "double";
        } else if (jsonNode.isObject()) {
            // 对象类型，递归生成
            return generateJavaClass(jsonNode.fieldNames().next(), jsonNode);
        } else {
            // 默认为Object类型
            return "Object";
        }
    }
}
